from cache import sockets
import cache
import query

import json


def push_partner_changed(username, partner):
    socket = sockets[username]
    history = query.get_history(partner)
    if history is None:
        return None
    values = {
        'action': 'partner-changed',
        'result': 'ok',
        'partner': partner,
        'success': history[0],
        'failure': history[1],
        'score': history[2]
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_first_partner(username):
    partner = cache.get_first_partner(username)
    if partner and len(partner):
        push_partner_changed(username, partner)
        push_partner_changed(partner, username)


def push_ready(username, self_ready):
    socket = sockets[username]
    values = {
        'action': 'partner-ready',
        'result': 'ok',
        'ready': self_ready
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_game_start(username, role):
    socket = sockets[username]
    values = {
        'action': 'game-start',
        'result': 'ok',
        'role': role
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_new_step(username, x, y):
    socket = sockets[username]
    values = {
        'action': 'new-step',
        'result': 'ok',
        'x': x,
        'y': y,
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_retract_ask(username):
    socket = sockets[username]
    values = {
        'action': 'retract-ask',
        'result': 'ok'
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_retract_answer(username, permission):
    socket = sockets[username]
    values = {
        'action': 'retract-answer',
        'result': 'ok',
        'permission': permission
    }
    response = json.dumps(values)
    socket.write_message(response)


def push_resign(username):
    socket = sockets[username]
    values = {
        'action': 'resign',
        'result': 'ok',
    }
    response = json.dumps(values)
    socket.write_message(response)
